<?php
require_once("inc.member.php");

$this_title="$vars[member_title] &raquo; ".__("Maintenance Topup");
$page_title=__("Maintenance Topup");
$content_title=__("Maintenance Topup");

$td_width=180;

$r_user=get_user_detail_by_id($uid);

require_once("inc.wallet_select.php");

$r_payment=array('ewallet');
$r_payment_d=array('ewallet'=>__($vars['ewallet_title'])." - ".__("Balance").": ".$vars['currency'].number_format($r_user['ewallet'], 2));

//#####TRANSFER POST#####
if($_POST["__req"]){
	$errmsg=verify_form_data("member_maintain", $post_s);
	if(!$errmsg){
		if(!strlen($post_s["password"])){
			$errmsg.=replace_tag(__("'<%field%>' is a required field."), array("<%field%>"=>__("Password")))."<br />\n";
		}else{
			$enc_pass=explode(":", $r_user["ewallet_enc_password"]);
			$salt=$enc_pass[1];
			if(md5($post_s["password"].$salt)!=$enc_pass[0]){
				$errmsg.=__("You have entered an invalid Password.")."<br />\n";
			}
		}
		if(!in_array($post_s['payment'], $r_payment)){
			$errmsg.=__("Please select a payment channel.")."<br />";
		}
		if(!$errmsg){
			if($r_user[$post_s['payment']]<$post_s['_amount']){
				$errmsg.=replace_tag(__("You do not have sufficient <%title%> for this transfer."), array("<%title%>"=>__($vars[$post_s['payment'].'_title'])))."<br />\n".replace_tag(__("<%title%> required: <%x%>"), array("<%title%>"=>__($vars['ewallet_title']), "<%x%>"=>number_format($post_s['_amount'], 2)))."<br />\n".replace_tag(__("<%title%> available: <%x%>"), array("<%title%>"=>__($vars[$post_s['payment'].'_title']), "<%x%>"=>number_format($r_user[$post_s['payment']], 2)))."<br />\n";
			}
		}
	}

	if(!$errmsg){
		$datetime=ndate();
		$topup_amount = $post_d[_amount];
		if($r_user['country']=='TH'){ 
			$rate = $vars['th_maintain_rate']; 
		} elseif($r_user['country']=='JP'){ 
			$rate = $vars['jp_maintain_rate']; 
		} else { 
			$rate = $vars['maintain_rate']; 
		}
		$bv = $topup_amount * $rate;
		
		if(!mysql_query($sql="update $db->users set ewallet=ewallet-$post_s[_amount], swallet=swallet+$bv where id='$uid' limit 1")){
			$errmsg.=__("We have encountered some error while performing the maintenance topup.")." ".__("You can try again later. If the problem persists, please contact us.")."<br />\n".($vars['debug']? "<br />\nSQL: $sql<br />\n<br />\nError: ".mysql_error()."<br />\n" : "");
		}else{
			//insert maintenance record
			$year = ndate('Y');
			$month = ndate('n');
			
			$sql = "insert into $db->member_maintain (uid, comm_type, credit, rate, amount, year, month, cdate) values ('$uid', 'um', '$topup_amount', '$rate', '$bv', '$year', '$month', '$datetime')";
			if(!mysql_query($sql)){
				$errmsg.=replace_tag(__("We have encountered an error while performing the maintenance topup. Your <%title%> account has been deducted <%x%> and <%title2%> has been credited with <%y%>, please contact us."), array("<%title%>"=>__($vars['ewallet_title']), "<%x%>"=>number_format($post_s['_amount'], 2), "<%title2%>"=>__($vars['swallet_title']), "<%y%>"=>number_format($post_s['_amount'], 2)))."<br />\n".($vars['debug']? "<br />\nSQL: $sql<br />\n<br />\nError: ".mysql_error()."<br />\n" : "");
				$critical_error.="Error performing the maintenance topup when member ID #$uid topup maintenance and the member ID #$uid $vars[ewallet_title] account has been deducted ".number_format($post_s['_amount'], 2)." and $vars[swallet_title] has been credited with ".number_format($post_s['_amount'], 2).", please contact us to undo the operation.<br /><br />\nSQL: $sql<br />\n<br />\nError: ".mysql_error()."<br />\n";
			}
			//insert ewallet record for maintenance
			if(!mysql_query($sql="insert into $db->member_ewallet_record (uid, type, amount, descr, cdate) values ('$uid', 'debit', '$post_d[_amount]', '".addslashes("Debited $vars[currency]".number_format($post_d['_amount'], 2)." for topup maintenance ".$bv."BV.")."', '".ndate()."')")){
				$critical_error.="Error recodring the $vars[ewallet_title] record while member topup maintenance.\n\nSQL:$sql\n\nError: ".mysql_error()."\n";
			}else{
				$new_eid = mysql_insert_id();
				$last_bal = @mysql_result(mysql_query("select bal from $db->member_ewallet_record where uid='$uid' and id!=$new_eid order by id desc limit 1"), 0);
				if(!$last_bal){
					$last_bal = 0;
				}
				$last_bal -= $post_d['_amount'];
				@mysql_query("update $db->member_ewallet_record set bal='$last_bal' where id='$new_eid' limit 1");
			}
			
			//insert swallet record for maintenance
			if(!mysql_query($sql="insert into $db->member_swallet_record (uid, type, amount, descr, cdate) values ('$uid', 'credit', '$bv', '".addslashes("Credited $vars[currency]".number_format($post_d['_amount'], 2)." for topup maintenance ".$bv."BV.")."', '".ndate()."')")){
				$critical_error.="Error recodring the $vars[swallet_title] record while member topup maintenance.\n\nSQL:$sql\n\nError: ".mysql_error()."\n";
			}else{
				$new_eid = mysql_insert_id();
				$last_bal = @mysql_result(mysql_query("select bal from $db->member_swallet_record where uid='$uid' and id!=$new_eid order by id desc limit 1"), 0);
				if(!$last_bal){
					$last_bal = 0;
				}
				$last_bal += $bv;
				@mysql_query("update $db->member_swallet_record set bal='$last_bal' where id='$new_eid' limit 1");
			}
		}

		if(!$errmsg){
			$msg=replace_tag(__("Your have successfully topup your maintenance by <%x%> point."), array("<%x%>"=>number_format($bv, 2)))."<br />\n";
			$r_user=get_user_detail_by_id($uid);
			$logstr = "Member ID#$r_user[username] ($uid) has successfully topup the maintenance account by ".number_format($bv, 2)." point.";
		}
	}

	$log_code = 'u-ewm';
	$affected_uid = $uid;
	if($critical_error){
		//log_activity('e', 'u', $uid, 'u', $affected_uid, $log_code, $critical_error);
		$a_sub="$vars[title] - Topup Maintenance Failure for Member ID #$uid";
		$a_msg="
		<p>Dear admin,</p>
		<p>$critical_error</p>";
		email_admin($a_sub, $a_msg, 'e');
	}elseif($logstr){
		$log_descr = $logstr;
		//log_activity('a', 'u', $uid, 'u', $affected_uid, $log_code, $log_descr);
	}

	$msg=$msg? format_msg($msg) : "";
	$errmsg=$errmsg? format_err(__("There is some error(s), please correct them before continuing:")."<br />\n<br />\n$errmsg") : "";
}

$form_fields=array("_amount"=>"","payment"=>"ewallet");
foreach($form_fields as $field => $default){
 $db_fieldname=preg_match('/^_/', $field)? substr($field, 1) : $field;
 $dis[$field]=(!$post_s["__req"]? $default : $post_h[$field]);
}
$payment_select = build_select($r_payment, $r_payment_d, $dis['payment'], 'payment', $inputbox_style);

//javascript
ob_start();
?>
<script type='text/javascript' src='<?php echo JS_URL."/get_file_gzip.php?file=".urlencode("fn/fn_number_format.js,common.js,jquery.js,jquery.livequery.js"); ?>'></script>
<script type='text/javascript'>
jQuery(document).ready(function(j){
	j('form[@name=maintain_form]').submit(function(){
		var confirm_text='<?php echo AddSlashes(__("Topup your maintenance by <#x#> points.")); ?>\n\n<?php echo AddSlashes(__("Are you sure?")); ?>';
		confirm_text=confirm_text.replace(/\<#x#\>/, number_format(j('input[@name=_amount]').val()*<?php if($r_user['country']=='TH'){ echo $vars['th_maintain_rate']; } elseif($r_user['country']=='JP'){ echo $vars['jp_maintain_rate']; } else { echo $vars['maintain_rate']; } ?>, 2));
		if(confirm(confirm_text)){
			j('input[@name=submit_btn]').attr('disabled','disabled');
		}else{
			return false;
		}
	});
});
</script>
<?php
$jvscript = ob_get_contents();
ob_end_clean();

//topup form
$topup=($errmsg || $msg? $errmsg.$msg : "").
"<p>".__("You can topup your maintenance here.")."</p>
<form name='maintain_form' method='post' action='$this_file'>
<input type='hidden' name='__req' value='1' />
<table class='pbt_table'>
	<tr>
		<td width='$td_width'>".__("Topup Amount").__(":")." ".__("*")."</td>
		<td><input type='text' name='_amount' value=\"$dis[amount]\" $inputbox_style /></td>
	</tr>
	<tr>
		<td width='$td_width'>".__("Topup Using").__(":")." ".__("*")."</td>
		<td>$payment_select</td>
	</tr>
	<tr>
		<td width='$td_width'>".__("e-Wallet Password").__(":")." ".__("*")."</td>
		<td><input type='password' name='password' $inputbox_style /></td>
	</tr>
	<tr>
		<td colspan='2' class='center' style='padding:20px 0 20px 0;'>
		<input type='submit' name='submit_btn' value=\"".__("Topup")."\" />
		</td>
	</tr>
</table>
</form>";

$content=$inc_wallet_select."<h2>$page_title</h2>".$topup;
print format_member_page($content, $this_title, $content_title, $jvscript . $inc_jvscript);
?>